﻿var solicitanteOC = new Ext.form.FormPanel({
    id: 'solicitanteOC',
    scroll: 'vertical',
    dockedItems: [
    {
        xtype: 'toolbar',
        docked: 'top',
        title: 'Creado por',
        items: [
        {
            xtype: 'button',
            text: 'Volver',
            ui: 'back',
            handler: function() {
                var SAPUserStore = Ext.getStore('SAPUserStore');
                validateUser(SAPUserStore); //validar login de usuario
                //---------------------------------------------------
                panelPrincipal.setActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                solicitanteOC.items.items[2].items.items[0].hide();
            }
        },
        {
            xtype: 'spacer'
        }]
    }],
    items: [
    {
        xtype: 'panel',
        layout: 'hbox',
        items: [
        {
            xtype: 'panel',
            flex: 1,
            styleHtmlContent: true,
            html: [
                '<div align="center"><img src="resources/img/contact.png" width="48" heigth="48"/></div>'
            ]
        },
        {
            xtype: 'dataview',
            store: 'solicitanteStore',
            scroll: false,
            flex: 1,
            styleHtmlContent: true,
            itemSelector: 'div.textoContacto',
            tpl: [
                '<tpl for=".">' +
                '<div class="textoContacto">{NAME_TEXT}<br />' +
                '{FUNCTION}<br />' +
                '{DEPARTMENT}</div>' +
                '</tpl>',
            ]
        }]
    },
    {
        xtype: 'fieldset',
        title: 'Información del Creador',
        defaults:
    	{
    	    labelWidth: '35%'
    	},
        items: [
        {
            xtype: 'urlfield',
            label: 'Teléfono',
            readOnly: true,
            name: 'TEL_NUMBER',
            listeners: {
                'focus': function(ele) {
                    var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                    var nro = solicitanteOC.getRecord().data.TEL_NUMBER;
                    if (nro) {
                        Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                            if (res == 'yes') {
                                window.location = 'tel:' + nro;
                            }
                        }, this);
                    }
                }
            }
        },
        {
            xtype: 'textfield',
            label: 'Extensión',
            name: 'TEL_EXTENS',
            readOnly: true
        },
        {
            xtype: 'urlfield',
            label: 'Móvil',
            name: 'MOB_NUMBER',
            readOnly: true,
            listeners: {
                'focus': function(ele) {
                    var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                    var nro = solicitanteOC.getRecord().data.MOB_NUMBER;
                    if (nro) {
                        Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                            if (res == 'yes') {
                                window.location = 'tel:' + nro;
                            }
                        }, this);
                    }
                }
            }
        },
        {
            xtype: 'urlfield',
            label: 'Correo',
            name: 'SMTP_ADDR',
            readOnly: true,
            listeners: {
                'focus': function(ele) {
                    var nombre = solicitanteOC.getRecord().data.NAME_TEXT;
                    var nro = solicitanteOC.getRecord().data.SMTP_ADDR;
                    if (nro) {
                        Ext.Msg.confirm('Contacto', 'Enviar correo a ' + nombre + "?", function(res) {
                            if (res == 'yes') {
                                window.location = 'mailto:' + nro;
                            }
                        }, this);
                    }
                }
            }
        }
        ]
    },
    {
        xtype: 'fieldset',
        title: 'Compañia',
        defaults:
    	{
    	    labelWidth: '35%'
    	},
        items: [
        {
            xtype: 'textareafield',
            label: 'Dirección',
            readOnly: true,
            listeners: {
                'beforeshow': function(ele) {
                    var record = solicitanteOC.getRecord();
                    ele.setValue(record.data.STREET + '\n' + record.data.CITY1 + '\n' + record.data.POST_CODE1);
                }
            }
        }]
    }]
});


var contactoOC = new Ext.form.FormPanel({
    id: 'contactoOC',
    scroll: 'vertical',
    dockedItems: [
    {
        xtype: 'toolbar',
        dock: 'top',
        title: 'Proveedor',
        items: [
        {
            xtype: 'button',
            text: 'Volver',
            ui: 'back',
            handler: function() {
                var SAPUserStore = Ext.getStore('SAPUserStore');
                validateUser(SAPUserStore); //validar login de usuario
                //---------------------------------------------------
                panelPrincipal.setActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                contactoOC.items.items[2].items.items[0].hide();
            }
        },
        {
            xtype: 'spacer'
        }]
    }],
    items: [
    {
        xtype: 'panel',
        layout: 'hbox',
        items: [
        {
            xtype: 'panel',
            flex: 1,
            styleHtmlContent: true,
            html: [
                '<div align="center"><img src="resources/img/contact.png" width="48" heigth="48"/></div>'
            ]
        },
        {
            xtype: 'dataview',
            store: 'contactoStore',
            scroll: false,
            flex: 1,
            styleHtmlContent: true,
            itemSelector: 'div.textoContacto',
            tpl: [
                '<tpl for=".">' +
                '<div class="textoContacto">{NAME_TEXT}<br />' +
                '{FUNCTION}<br />' +
                '{DEPARTMENT}</div>' +
                '</tpl>',
            ]
        }]
    },
    {
        xtype: 'fieldset',
        title: 'Información del Proveedor',
        defaults:
	    {
	        labelWidth: '35%'
	    },
        items: [
        {
            xtype: 'urlfield',
            label: 'Teléfono',
            name: 'TEL_NUMBER',
            readOnly: true,
            listeners: {
                'focus': function(ele) {
                    var nombre = contactoOC.getRecord().data.NAME_TEXT;
                    var nro = contactoOC.getRecord().data.TEL_NUMBER;
                    if (nro) {
                        Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                            if (res == 'yes') {
                                window.location = 'tel:' + nro;
                            }
                        }, this);
                    }
                }
            }
        },
        {
            xtype: 'textfield',
            label: 'Extensión',
            name: 'TEL_EXTENS',
            readOnly: true
        },
        {
            xtype: 'urlfield',
            label: 'Móvil',
            name: 'MOB_NUMBER',
            readOnly: true,
            listeners: {
                'focus': function(ele) {
                    var nombre = contactoOC.getRecord().data.NAME_TEXT;
                    var nro = contactoOC.getRecord().data.MOB_NUMBER;
                    if (nro) {
                        Ext.Msg.confirm('Contacto', 'Llamar a ' + nombre + "?", function(res) {
                            if (res == 'yes') {
                                window.location = 'tel:' + nro;
                            }
                        }, this);
                    }
                }
            }
        },
        {
            xtype: 'urlfield',
            label: 'Correo',
            name: 'SMTP_ADDR',
            readOnly: true,
            listeners: {
                'focus': function(ele) {
                    var nombre = contactoOC.getRecord().data.NAME_TEXT;
                    var nro = contactoOC.getRecord().data.SMTP_ADDR;
                    if (nro) {
                        Ext.Msg.confirm('Contacto', 'Enviar correo a ' + nombre + "?", function(res) {
                            if (res == 'yes') {
                                window.location = 'mailto:' + nro;
                            }
                        }, this);
                    }
                }
            }
        }]
    },
    {
        xtype: 'fieldset',
        title: 'Compañia',
        defaults:
	    {
	        labelWidth: '35%'
	    },
        items: [
        {
            xtype: 'textareafield',
            label: 'Dirección',
            readOnly: true,
            listeners: {
                'beforeshow': function(ele) {
                    var record = contactoOC.getRecord();
                    ele.setValue(record.data.STREET + '\n' + record.data.CITY1 + '\n' + record.data.POST_CODE1);
                }
            }
        }]
    }]
});

var itemOC = new Ext.form.FormPanel({
    id: 'itemOC',
    scroll: 'vertical',
    dockedItems: [
    {
        xtype: 'toolbar',
        docked: 'top',
        title: 'Posición',
        items: [
        {
            xtype: 'button',
            text: 'Volver',
            ui: 'back',
            handler: function() {
                var SAPUserStore = Ext.getStore('SAPUserStore');
                validateUser(SAPUserStore); //validar login de usuario
                //---------------------------------------------------
                panelPrincipal.setActiveItem(detalleOC, { type: 'slide', direction: 'right' });
                itemOC.items.items[0].items.items[1].hide();
                itemOC.items.items[0].items.items[2].hide();
                itemOC.items.items[0].items.items[3].hide();
                itemOC.items.items[0].items.items[5].hide();
                itemOC.items.items[0].items.items[6].hide();
            }
        },
        {
            xtype: 'spacer'
        }]
    }],
    items:[
    {
        xtype: 'fieldset',
        title: 'Datos de Posición',
        defaults:
    	{
    	    labelWidth: '35%'
    	},
        items: [
        {
            xtype: 'textfield',
            label: 'Nro. de Pos.',
            name: 'Pos',
            readOnly: true
        },
        {
            xtype: 'textfield',
            label: 'Cantidad',
            readOnly: true,
            listeners: {
                'beforeshow': function(ele) {
                    var record = itemOC.getRecord();
                    ele.setValue(record.data.Cant + ' ' + record.data.UM);
                }
            }
        },
        {
            xtype: 'textfield',
            label: 'Precio Unit.',
            readOnly: true,
            listeners: {
                'beforeshow': function(ele) {
                    var record = itemOC.getRecord();
                    ele.setValue(record.data.Precio + ' ' + record.data.Moneda);
                }
            }
        },
        {
            xtype: 'textfield',
            label: 'CeCo',
            readOnly: true,
            listeners: {
                'beforeshow': function(ele) {
                    var record = itemOC.getRecord();
                    ele.setValue(record.data.CentCO + ' - ' + record.data.DescCentCO);
                }
            }
        },
        {
            xtype: 'textfield',
            label: 'Responsable CO',
            name: 'NombRespCO',
            readOnly: true
        },
        {
            xtype: 'textfield',
            label: 'Orden',
            readOnly: true,
            listeners: {
                'beforeshow': function(ele) {
                    var record = itemOC.getRecord();
                    ele.setValue(record.data.NroOrd + ' - ' + record.data.DescNroOrd);
                }
            }
        },
        {
            xtype: 'textfield',
            label: 'Activo Fijo',
            name: 'ActFijo',
            readOnly: true
        }]
    }],
    listeners: {
        'render': function(ele) {
            var rec = ele.getRecord();
            if (rec) {
                ele.loadRecord(rec);
            }    
        }    
    }
});

var form = new Ext.form.FormPanel({
    id: 'form',
    scroll: false,
    items: [
    {
        xtype: 'button',
        text: 'Liberar',
        ui: 'action',
        handler: function() {
            var SAPUserStore = Ext.getStore('SAPUserStore');
            validateUser(SAPUserStore); //validar login de usuario
            //---------------------------------------------------
            if (navigator.onLine) {
                var LibCod = detalleOC.getRecord().data.LibCod;
                var PO = detalleOC.getRecord().data.PO;
                var sto = Ext.getStore('accesoStore');
                var SAPUserStore = Ext.getStore('SAPUserStore');
                var host = sto.last().data.hostValue;
                form.add({ xtype: 'hiddenfield', id: 'LibCod', name: 'LibCod', value: LibCod });
                form.add({ xtype: 'hiddenfield', id: 'PO', name: 'PO', value: PO });
                prepareForm(form, SAPUserStore); //@@@
                form.submit({
                    method: 'POST',
                    url: host + '/release.aspx',
                    waitMsg: { message: 'Conectando ...', cls: 'demos-loading' },
                    success: function(form, action) {
                        if (action.success) {
                            Ext.Msg.alert('Aviso', action.errors.reason);
                            panelFloat.hide();
                            var sto = listaOC.getStore().data.items;
                            for (var i = 0; i < sto.length; i++) {
                                var currentPO = sto[i];
                                if (currentPO.data.PO == PO) {
                                    listaOC.getStore().remove(currentPO);
                                    listaOC.getStore().sync();
                                    listaOC.refresh();
                                    panelPrincipal.setActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                                }
                            }
                        }
                        else {
                            Ext.Msg.alert('Error', action.errors.reason);
                        }
                    },
                    failure: function(form, action) {
                        if (action.errors) {
                            Ext.Msg.alert('Error', action.errors.reason);
                        }
                        else {
                            Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                        }
                    }
                });
            }
            else {
                Ext.Msg.alert('Error', 'Verifique la conexión a internet');
            }
        }
    },
    {
        xtype: 'button',
        text: 'Cancelar',
        ui: 'normal',
        handler: function() {
            panelFloat.hide();
        }
    }]
});

var panelFloat = new Ext.Panel({
    id: 'panelFloat',
    floating: true,
    centered: true,
    modal: true,
    items: [form],
    listeners: {
        'beforeshow': function(ele) {
            if (Ext.is.Blackberry) {
                ele.setWidth(130);
                ele.setHeight(100)
                ele.items.items[0].items.items[0].setSize(90, 30);
                ele.items.items[0].items.items[1].setSize(90, 30);
            }
            else {
                var w = detalleOC.getWidth();
                var h = detalleOC.getHeight();
                ele.setWidth(w / 3);
                ele.setHeight(h / 4);
            }
        }
    }
});

var detalleOC = new Ext.form.FormPanel({
    id: 'detalleOC',
    scroll: 'vertical',
    dockedItems: [
    {
        xtype: 'toolbar',
        dock: 'top',
        title: 'Detalle',
        items: [
        {
            xtype: 'button',
            text: 'Volver',
            ui: 'back',
            handler: function() {
                var SAPUserStore = Ext.getStore('SAPUserStore');
                validateUser(SAPUserStore); //validar login de usuario
                //---------------------------------------------------
                panelPrincipal.setActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
                detalleOC.items.items[0].items.items[3].hide();
            }
        },
        {
            xtype: 'spacer'
        }]
    },
    {
        xtype: 'toolbar',
        id: 'tbLiberar',
        dock: 'bottom',
        items: [
        {
            xtype: 'button',
            text: 'Liberar',
            id: 'btnLiberar',
            ui: 'confirm',
            handler: function() {
                var SAPUserStore = Ext.getStore('SAPUserStore');
                validateUser(SAPUserStore); //validar login de usuario
                //---------------------------------------------------
                panelFloat.showBy(detalleOC.getComponent('tbLiberar').getComponent('btnLiberar'));
            }
        },
        {
            xtype: 'spacer'
        },
        {
            xtype: 'button',
            text: 'Cancelar',
            ui: 'decline',
            handler: function() {
                var SAPUserStore = Ext.getStore('SAPUserStore');
                validateUser(SAPUserStore); //validar login de usuario
                //---------------------------------------------------
                panelPrincipal.setActiveItem(listaOCPanel, { type: 'slide', direction: 'right' });
            }
        }]
    }],
    items: [
    {
        xtype: 'fieldset',
        title: 'Datos',
        items: [
        {
            xtype: 'textfield',
            label: 'Nro. Doc.',
            name: 'PO',
            readOnly: true
        },
        {
            xtype: 'textfield',
            label: 'Tipo Doc.',
            name: 'ClaseDocT',
            readOnly: true
        },
        {
            xtype: 'textfield',
            label: 'Sociedad',
            name: 'NomSoc',
            readOnly: true
        },
        {
            xtype: 'textfield',
            label: 'Monto Total',
            readOnly: true,
            listeners: {
                'beforeshow': function(ele) {
                    var record = detalleOC.getRecord();
                    ele.setValue(record.data.TotBruto + ' ' + record.data.Moneda);
                }
            }
        },
        {
            xtype: 'textareafield',
            label: 'Texto',
            name: 'Texto',
            readOnly: true
        }]
    },
    {
        xtype: 'fieldset',
        title: 'Creado por',
        items: [
        {
            xtype: 'textfield',
            label: 'Nombre',
            name: 'NomSolicitante',
            readOnly: true,
            listeners: {
                'focus': function(ele) {
                    var rec = detalleOC.getRecord().data.CodUsuario;
                    var sto = Ext.getStore('solicitanteStore');
                    var solicitante = sto.findRecord('BNAME', rec);
                    if (solicitante) {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        solicitanteOC.reset();
                        solicitanteOC.loadRecord(solicitante);
                        solicitanteOC.items.items[0].items.items[1].refresh();
                        solicitanteOC.items.items[2].items.items[0].show();
                        panelPrincipal.setActiveItem(solicitanteOC, { type: 'slide', direction: 'left' });
                    }
                }
            }
        }]
    },
    {
        xtype: 'fieldset',
        title: 'Proveedor',
        items: [
        {
            xtype: 'textfield',
            label: 'Nombre',
            name: 'DescProveedor',
            readOnly: true,
            listeners: {
                'focus': function(ele) {
                    var rec = detalleOC.getRecord().data.CodProveedor;
                    var sto = Ext.getStore('contactoStore');
                    var contacto = sto.findRecord('LIFNR', rec);
                    if (contacto) {
                        var SAPUserStore = Ext.getStore('SAPUserStore');
                        validateUser(SAPUserStore); //validar login de usuario
                        contactoOC.reset();
                        contactoOC.loadRecord(contacto);
                        contactoOC.items.items[0].items.items[1].refresh();
                        contactoOC.items.items[2].items.items[0].show();
                        panelPrincipal.setActiveItem(contactoOC, { type: 'slide', direction: 'left' });
                    }
                }
            }
        }]
    },
    {
        xtype: 'fieldset',
        title: 'Productos',
        items: [
        {
            xtype: 'list',
            store: 'itemStore',
            scroll: false,
            layout: 'fit',
            allowDeselect: true,
            itemTpl:
            '<div class="getAutoHeight">' +
            '<div class="doc-img"><img src="resources/img/item.png" width="20" height="20">' +
            '</div>' +
            '<div class="list-list">' +
                '<div style="font-weight:bold">{Desc}</div>' +
            '{Cant} {UM}&nbsp;x&nbsp;{Precio}&nbsp;{Moneda}' +
            '<br />' +
            '{Total}&nbsp;{Moneda}' +
            '</div>' +
            '<div class="doc-img2"><img src="resources/img/arrow.png" width="20" height="20">' +
            '</div>',
            listeners: {
                itemtap: function(list, index, element) {
                    var SAPUserStore = Ext.getStore('SAPUserStore');
                    validateUser(SAPUserStore); //validar login de usuario
                    //---------------------------------------------------
                    var record = list.getRecord(element);
                    itemOC.reset();
                    itemOC.loadRecord(record);
                    itemOC.dockedItems.items[0].setTitle('Posición ' + ltrim(record.data.Pos));
                    itemOC.items.items[0].setTitle(record.data.Desc);
                    itemOC.items.items[0].items.items[1].show();
                    itemOC.items.items[0].items.items[2].show();
                    itemOC.items.items[0].items.items[3].show();
                    itemOC.items.items[0].items.items[5].show();
                    itemOC.items.items[0].items.items[6].show();
                    panelPrincipal.setActiveItem(itemOC, { type: 'slide', direction: 'left' });
                }
            }
        }]
    }]
});


var listaOC = new Ext.List({
    id: 'listaOC',
    store: 'ordenCompraStore',
    allowDeselect: true,
    scroll: false,
    layout: 'fit',
    loadingText: 'Cargando Órdenes...',
    deferEmptyText : false,
    emptyText: 'No hay Órdenes pendientes de liberar',
    itemTpl:
    '<div class="getAutoHeight">' +
    '<div class="doc-img"><img src="resources/img/shopping_cart.png" width="30" height="30"></div>' +
        '<div class="list-doci">' +
            '<div style="font-weight:bold;">{DescProveedor}</div>' +
        '{PO}&nbsp;&nbsp;-&nbsp;&nbsp;{NomSolicitante}' +
        '</div>' +
        '<div class="list-docd">' +
            '<div style="font-weight:bold;">{TotBruto}&nbsp;&nbsp;{Moneda}</div>' +
        '{Fecha}' +
        '</div>' +
    '<div class="doc-img2"><img src="resources/img/arrow.png" width="20" height="20"></div>' +
    '</div>',
    listeners: {
        itemtap: function(list, index, element) {
            var SAPUserStore = Ext.getStore('SAPUserStore');
            validateUser(SAPUserStore); //validar login de usuario
            //---------------------------------------------------
            var record = listaOC.getRecord(element);
            detalleOC.loadRecord(record);
            var PO = record.data.PO;
            var sto = Ext.getStore('itemStore');
            sto.getProxy().clear();
            sto.data.clear();
            sto.sync();
            sto.add(record.data.Items);
            sto.sync();
            var sto = Ext.getStore('contactoStore');
            sto.getProxy().clear();
            sto.data.clear();
            sto.sync();
            sto.add(record.data.Contactos);
            sto.sync();
            var sto = Ext.getStore('solicitanteStore');
            sto.getProxy().clear();
            sto.data.clear();
            sto.sync();
            sto.add(record.data.Solicitantes);
            sto.sync();
            detalleOC.items.items[3].items.items[0].refresh();
            detalleOC.dockedItems.items[0].setTitle('Ord. Compra');
            detalleOC.items.items[0].items.items[3].show();
            panelPrincipal.setActiveItem(detalleOC, { type: 'slide', direction: 'left' });
        }
    }
});

var listaOCPanel = new Ext.form.FormPanel({
    id: 'listaOCPanel',
    scroll: 'vertical',
    dockedItems: [
    {
        xtype: 'toolbar',
        title: 'Lista',
        dock: 'top',
        items: [
        {
            xtype: 'button',
            ui: 'decline',
            text: 'Salir',
            handler: function() {
                window.localStorage.clear();
                loginForm.reset();
                panelPrincipal.setActiveItem(loginForm, { type: 'slide', direction: 'right' });
            }
        },
        {
            xtype: 'spacer'
        }]
    },
    {
        xtype: 'toolbar',
        dock: 'bottom',
        items: [
        {
            xtype: 'button',
            ui: 'confirm',
            iconCls: 'refresh',
            iconMask: true,
            handler: function() {
                var SAPUserStore = Ext.getStore('SAPUserStore');
                validateUser(SAPUserStore); //validar login de usuario
                //---------------------------------------------------
                if (navigator.onLine) {
                    var sto = Ext.getStore('accesoStore');
                    var SAPUserStore = Ext.getStore('SAPUserStore');
                    var host = sto.last().data.hostValue;
                    prepareForm(listaOCPanel, SAPUserStore); //@@@
                    listaOCPanel.submit({
                        method: 'POST',
                        url: host + '/List.aspx',
                        waitMsg: { message: 'Conectando ...', cls: 'demos-loading' },
                        success: function(form, action) {
                            if (action.success) {
                                listaOC.getStore().getProxy().clear();
                                listaOC.getStore().data.clear();
                                listaOC.getStore().sync();
                                listaOC.refresh();
                                listaOC.getStore().add(action.lstItemsResale);
                                listaOC.getStore().sync();
                                var now = new Date();
                                listaOCPanel.dockedItems.items[1].setTitle('Actualizado  al ' + now.getDate() + '.' + (now.getMonth() + 1) + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + now.getMinutes());
                            }
                            else {
                                Ext.Msg.alert('Error', action.errors.reason);
                            }
                        },
                        failure: function(form, action) {
                            //Falta manejo de error por timeout
                            if (action.errors) {
                                Ext.Msg.alert('Error', action.errors.reason);
                            }
                            else {
                                Ext.Msg.alert('Error', 'Status: ' + action.status + ' - ' + action.statusText);
                            }
                        }
                    });
                }
                else {
                    Ext.Msg.alert('Error', 'Verifique la conexión a internet');
                }
            }
        },
        {
            xtype: 'spacer'
        },
        {
            xtype: 'spacer' 
        }]
    }],
    items: [listaOC]
});

var accesoForm = new Ext.form.FormPanel({
    id: 'accesoForm',
    scroll: 'vertical',
    dockedItems:[
    {
        xtype: 'toolbar',
        dock: 'top',
        title: 'Accesos'
    },
    {
        xtype: 'toolbar',
	    dock: 'bottom',
	    items: [
	    {
	        xtype: 'button',
	        text: 'Volver',
	        ui: 'dark',
	        handler: function() {
	            panelPrincipal.setActiveItem(loginForm, { type: 'slide', direction: 'left' });
	        }
	    },
        {
            xtype: 'spacer'
        },
        {
            xtype: 'button',
            text: 'Grabar',
            ui: 'confirm',
            handler: function() {
                var ser = accesoForm.getValues().servidor;
                var nom = accesoForm.getValues().nombre;
                var pue = accesoForm.getValues().puerto;
                var pro = accesoForm.getValues().protocolo;
                if (ser == '' && nom == '' && pue == '' && pro == '') {
                    Ext.Msg.alert("Aviso", 'Verifique los campos ingresados');
                }
                else {
                    hostValue(ser, nom, pue, pro, panelPrincipal);
                }
            }
        }]
    }],
    items:[
    {
	    xtype: 'fieldset',
	    title: 'Parámetros conexión al sistema',
	    defaults:
    	{
    	    labelWidth: '50%'
    	},
	    items: [
		{
		    xtype: 'textfield',
		    label: 'Servidor de aplicación',
		    name: 'servidor',
		    placeHolder: 'Ingrese servidor'
		},
		{
		    xtype: 'textfield',
		    label: 'Nombre de la aplicación',
		    name: 'nombre',
		    placeHolder: 'Ingrese nombre del app'
		},
		{
		    xtype: 'textfield',
		    label: 'Puerto',
		    name: 'puerto',
		    placeHolder: 'Ingrese puerto'
		},
		{
		    xtype: 'textfield',
		    label: 'Protocolo',
		    name: 'protocolo',
		    placeHolder: 'Ingrese protocolo'
        }]
    }],
    listeners: {
        'render': function(ele) {
            var sto = Ext.getStore('accesoStore');
            var rec = sto.last();
            if (rec) {
                ele.loadRecord(rec);
            }
        }    
    }    
});

var loginForm = new Ext.form.FormPanel({
    id: 'formDoc',
    scroll: 'vertical',
    dockedItems:[
    {
        xtype: 'toolbar',
        dock: 'bottom',
        items: [
        {
            xtype: 'button',
            text: 'Accesos',
            ui: 'dark',
            handler: function() {
                var sto = Ext.getStore('accesoStore');
                var rec = sto.last();
                if (rec) {
                    if (rec.data.servidor == defServidor && rec.data.nombre == defNombre && rec.data.puerto == defPuerto && rec.data.protocolo == defProtocolo) {
                        sto.getProxy().clear();
                        sto.data.clear();
                        sto.sync();
                    }
                }
                panelPrincipal.setActiveItem(accesoForm, { type: 'slide', direction: 'right' });
            }
        },
        {
            xtype: 'spacer'
        },
        {
            xtype: 'button',
            text: 'Entrar',
            ui: 'confirm',
            handler: function() {
                if (navigator.onLine) {
                    var sto = Ext.getStore('accesoStore');
                    if (!sto.last()) {//cargar accesos por default
                        hostValue(defServidor, defNombre, defPuerto, defProtocolo, 'loginForm');
                    }
                    var host = sto.last().data.hostValue;
                    var loUser = Ext.ModelMgr.create({
                        Uname: loginForm.getValues().usuario,
                        Passwd: loginForm.getValues().clave,
                        Langu: loginForm.getValues().idioma
                    }, 'SAPUserBE');
                    var errors = loUser.validate();
                    var message = "";
                    if (!errors.isValid()) {
                        errors.each(function(item, index, length) {
                            message += item.getMessage() + "<br>";
                        });
                        Ext.Msg.alert("Error", message, function() { });
                        return false;
                    }
                    loginForm.submit({
                        method: 'POST',
                        url: host + '/login.aspx',
                        waitMsg: { message: 'Conectando ...', cls: 'demos-loading' },
                        success: function(form, action) {
                            if (!action) { Ext.Msg.alert('Error', 'Verifique los parámetros de acceso'); }
                            else {
                                if (action.success) {
                                    var SAPUserStore = Ext.getStore('SAPUserStore');
                                    var loUser = new SAPUserBE(action.user);
                                    SAPUserStore.add(loUser);
                                    SAPUserStore.sync();
                                    listaOC.getStore().getProxy().clear();
                                    listaOC.getStore().data.clear();
                                    listaOC.getStore().sync();
                                    listaOC.refresh();
                                    listaOC.getStore().add(action.lstItemsResale);
                                    listaOC.getStore().sync();
                                    var now = new Date();
                                    listaOCPanel.dockedItems.items[1].setTitle('Actualizado  al ' + now.getDate() + '.' + (now.getMonth() + 1) + '.' + now.getFullYear() + '  ' + now.getHours() + ':' + now.getMinutes());
                                    panelPrincipal.setActiveItem(listaOCPanel, { type: 'slide', direction: 'left' });
                                }
                                else {
                                    Ext.Msg.alert('Error', action.errors.reason);
                                }
                            }
                        },
                        failure: function(form, action) {
                            if (!action.errors || !action.errors.reason)
                            { Ext.Msg.alert('Error', 'Verifique los parámetros de acceso'); }
                            else {
                                Ext.Msg.alert('Error', action.errors.reason);
                            }
                        }
                    });
                }
                else {
                    Ext.Msg.alert('Error', 'Verifique la conexión a internet');
                }
            }
        }]
    }],
    items:[
    {
        xtype: 'fieldset',
        title: nombreEmpresa
    },
    {
        xtype: 'fieldset',
        items: [
        {
            xtype: 'textfield',
            id: 'usuario',
            name: 'usuario',
            label: 'Usuario',
            useClearIcon: true,
            required: true,
            value: '',
            placeHolder: 'Ingrese usuario'
        },
        {
            xtype: 'passwordfield',
            id: 'clave',
            name: 'clave',
            label: 'Clave',
            useClearIcon: true,
            required: true,
            value: '',
            placeHolder: 'Ingrese contraseña'
        }]
    },
    {
        xtype: 'fieldset',
        hidden: true,
        items: [
        {
            xtype: 'selectfield',
            id: 'idioma',
            name: 'idioma',
            label: 'Idioma',
            options: [
            {
                text: 'Español',
                value: 'ES'
            }]
        }]
    }]
});

var introForm = new Ext.form.FormPanel({
    id: 'introForm',
    scroll: 'false',
    layout: 'hbox',
    centered: true,
    bodyStyle: 'background-color:#ffffff;',
    items:[
    {
        xtype: 'panel',
        flex: 1,
        centered: true,
        scroll: false,
        styleHtmlContent: true,
        bodyStyle: 'background-color:#ffffff;',        
        html: [
            '<div align="center"><img src="resources/img/logo.png"/></div>'
        ]
    }],
    listeners: {
        'afterrender': function(ele) {
            Tick(ele.ownerCt,loginForm);
            //ele.ownerCt.setActiveItem(loginForm, { type: 'slide', direction: 'right', duration: 300 });
        }
    }
});

panelPrincipal = Ext.extend(Ext.Panel,
{
    id: 'panelPrincipal',
    fullscreen: true,
    layout: 'card',
    cardSwitchAnimation: 'slide',
    items: [introForm, loginForm, accesoForm, listaOCPanel, detalleOC, itemOC, contactoOC, solicitanteOC]
});

Ext.reg('panelPrincipal', panelPrincipal);